package com.ruoyi.web.controller.process;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.system.domain.SysDictData;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.process.ProcessInventory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.processService.IProcessInventoryService;
import com.ruoyi.web.websocket.JxlsUtils;
import com.ruoyi.web.websocket.QRCodeUtil;

/**
 * 加工库存Controller
 * 
 * @author ljx
 * @date 2020-07-06
 */
@Controller
@RequestMapping("/process/inventory")
public class ProcessInventoryController extends BaseController
{
	private static final Logger logger = LoggerFactory.getLogger(ProcessInventoryController.class);
    private String prefix = "process/inventory";

    @Resource
    private IProcessInventoryService processInventoryService;
    @Resource
    private ISysConfigService iSysConfigService;
    @Resource
    private DictService dictService;

    @RequiresPermissions("process:inventory:view")
    @GetMapping()
    public String inventory()
    {
        return prefix + "/inventory";
    }
    

    /**
     * 查询加工库存列表
     */
    @RequiresPermissions("process:inventory:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProcessInventory processInventory)
    {
        startPage();
        List<ProcessInventory> list = processInventoryService.selectProcessInventoryList(processInventory);
        return getDataTable(list);
    }

    /**
     * 导出加工库存列表
     */
    @RequiresPermissions("process:inventory:export")
    @Log(title = "加工库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ProcessInventory processInventory)
    {
        List<ProcessInventory> list = processInventoryService.selectProcessInventoryList(processInventory);
        ExcelUtil<ProcessInventory> util = new ExcelUtil<ProcessInventory>(ProcessInventory.class);
        return util.exportExcel(list, "inventory");
    }

    /**
     * 新增加工库存
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存加工库存
     */
    @RequiresPermissions("process:inventory:add")
    @Log(title = "加工库存", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ProcessInventory processInventory)
    {
        processInventory.setSpecificationUnit("mm");
        processInventory.setCreateBy(ShiroUtils.getLoginName());
        //默认加工状态为未加工
        processInventory.setStatus(1);
        return processInventoryService.insertProcessInventory(processInventory);
    }

    /**
     * 修改加工库存
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
    	ProcessInventory processInventory = processInventoryService.selectProcessInventoryById(id);
    	if(processInventory.getStatus()==1){
            processInventory.setStatusN("未加工");
        }else if(processInventory.getStatus()==2){
            processInventory.setStatusN("并卷");
        }else if(processInventory.getStatus()==3){
            processInventory.setStatusN("镀铝");
        }else if(processInventory.getStatus()==4){
            processInventory.setStatusN("分卷");
        }
        mmap.put("processInventory", processInventory);
    	mmap.put("fact",dictService.getType("factory_name").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        mmap.put("mate",dictService.getType("materials_name").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        mmap.put("spec",dictService.getType("m_specification").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        return prefix + "/edit";
    }
    
    
    @GetMapping("/editInfo/{id}")
    public String editInfo(@PathVariable("id") Long id, ModelMap mmap)
    {
    	ProcessInventory processInventory = processInventoryService.selectProcessInventoryById(id);
    	if(processInventory.getStatus()==1){
            processInventory.setStatusN("未加工");
        }else if(processInventory.getStatus()==2){
            processInventory.setStatusN("并卷");
        }else if(processInventory.getStatus()==3){
            processInventory.setStatusN("镀铝");
        }else if(processInventory.getStatus()==4){
            processInventory.setStatusN("分卷");
        }
        mmap.put("processInventory", processInventory);
    	mmap.put("fact",dictService.getType("factory_name").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        mmap.put("mate",dictService.getType("materials_name").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
        mmap.put("spec",dictService.getType("m_specification").stream().map(SysDictData::getDictValue).collect(Collectors.toList()));
    	
        return prefix + "/editInfo2";
    }
    
    @PostMapping( "/gzd")
    @ResponseBody
    public AjaxResult gzd(String ids)
    {
    	List<ProcessInventory> selectProcessInventoryListByIds = processInventoryService.selectProcessInventoryListByIds(ids);
    	for (ProcessInventory processInventory : selectProcessInventoryListByIds) {
			if (processInventory.getType().intValue() == 1) {
				return AjaxResult.error("不能选择出库的", null);
			}
		}
        return AjaxResult.success();
    }
    @GetMapping( "/gzdd")
    @ResponseBody
    public void gzdd(String ids,HttpServletRequest request,HttpServletResponse response) throws Exception
    {
    	 Map<String , Object> model=new HashMap<String , Object>();
    	List<ProcessInventory> selectProcessInventoryListByIds = processInventoryService.selectProcessInventoryListByIds(ids);
    	for (ProcessInventory processInventory : selectProcessInventoryListByIds) {
			if (processInventory.getType().intValue() == 1) {
				return ;
			}
		}
    	processInventoryService.diviy(selectProcessInventoryListByIds);
    	 String filename = new String("发货单".getBytes("gb2312"), "iso8859-1");  
         response.setHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");  
         model.put("list", selectProcessInventoryListByIds);
         model.put("tt", DateUtils.parseDateToStr(DateUtils.YYYYMMDD, new Date()));
//         InputStream inputStream = this.getClass().getClassLoader().getSystemResourceAsStream("chuku.xlsx");
         ClassPathResource resource = new ClassPathResource("chuku.xlsx");
         InputStream inputStream = resource.getInputStream();
         JxlsUtils.exportExcel(inputStream, response.getOutputStream(), model);
    }
    
    
    @GetMapping("/gExcelJson")
    @ResponseBody
    public AjaxResult gExcelJson(HttpServletRequest request,HttpServletResponse response) throws Exception
    {
    	ProcessInventory processInventory = new ProcessInventory();
		List<ProcessInventory> selectProcessInventoryListByIds = processInventoryService.selectProcessInventoryList(processInventory );
		return AjaxResult.success(selectProcessInventoryListByIds);
    }
    
   
    /**
     * 修改加工库存
     */
    @GetMapping("/print")
    public String print(String ids,ModelMap mmap)
    {
        mmap.put("ids", ids);
        return prefix + "/print";
    }
    
    @GetMapping("/gExcelJsonP")
    @ResponseBody
    public AjaxResult gExcelJsonP(String ids, HttpServletRequest request,HttpServletResponse response) throws Exception
    {
    	List<ProcessInventory> selectProcessInventoryListByIds = processInventoryService.selectProcessInventoryListByIds(ids);
    	String selectConfigByKey = iSysConfigService.selectConfigByKey("ttt");
    	String selectConfigByKey2 = iSysConfigService.selectConfigByKey("ttt2");
      	for (ProcessInventory processInventory : selectProcessInventoryListByIds) {
      		
          	processInventory.setMmm("常州市方鼎真空镀铝有限公司");
          	processInventory.setTtt("跟踪单");
          	processInventory.setImageUrl(selectConfigByKey2);
          	processInventory.setCreateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, processInventory.getCreateTime()));
          	
          	BufferedImage encode = QRCodeUtil.encode(selectConfigByKey + "process/inventory/editInfo/"+processInventory.getId(), null, true);
          	try{
	   		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	   		    ImageIO.write( encode, "png", baos );
	   		    baos.flush();
	   		    //使用toByteArray()方法转换成字节数组
	   		    byte[] imageInByte = baos.toByteArray();
	   		    baos.close();
	//   		    model.put("im", imageInByte);
	   		    String uploadNew = FileUploadUtils.uploadNew(imageInByte);
	   		    logger.error("uploadNew---"+uploadNew);
	   		   logger.error("selectConfigByKey---"+selectConfigByKey);
	   		    processInventory.setCodeUrl(selectConfigByKey+uploadNew);
	   	    }catch(IOException e){
	   	        System.out.println(e.getMessage());
	   	    }
          	
      	}
    	
    	
		return AjaxResult.success(selectProcessInventoryListByIds);
    }
    
    
    
    @GetMapping("/gExcel")
    @ResponseBody
    public void gExcel(String ids,HttpServletRequest request,HttpServletResponse response) throws Exception
    {
//    	ProcessInventory processInventory = processInventoryService.selectProcessInventoryById(id);
    	List<ProcessInventory> selectProcessInventoryListByIds = processInventoryService.selectProcessInventoryListByIds(ids);
    	String selectConfigByKey = iSysConfigService.selectConfigByKey("ttt");
    	 Map<String , Object> model2=new HashMap<String , Object>();
    	 List<Map<String, Object>>  maps = new ArrayList<Map<String,Object>>();
    	 ClassPathResource resource2 = new ClassPathResource("aa.png");
         InputStream inputStream2 = resource2.getInputStream();
         
     	ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
	  	  byte[] buffer=new byte[1024];
	  	  int ch;
	  	  /**
	  	   *
	  	   * */
	  	  while ((ch = inputStream2.read(buffer)) != -1) {
	  	   bytestream.write(buffer,0,ch);
	  	  }
	  	  byte data[] = bytestream.toByteArray();
	  	  bytestream.close();
  	  
    	for (ProcessInventory processInventory : selectProcessInventoryListByIds) {
    		
        	processInventory.setMmm("常州市方鼎真空镀铝有限公司");
        	processInventory.setTtt("跟踪单");
        	processInventory.setCreateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, processInventory.getCreateTime()));
        	processInventory.setImageInByte(data);
    		//http://demo.tc-keji.com/index
//        	BufferedImage encode = QRCodeUtil.encode(processInventory.getId()+"", null, true);
        	BufferedImage encode = QRCodeUtil.encode(selectConfigByKey + "process/inventory/editInfo/"+processInventory.getId(), null, true);
        	 Map<String , Object> model=new HashMap<String , Object>();
        	 try{
    		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		    ImageIO.write( encode, "png", baos );
    		    baos.flush();
    		    //使用toByteArray()方法转换成字节数组
    		    byte[] imageInByte = baos.toByteArray();
    		    baos.close();
//    		    model.put("im", imageInByte);
    		    
    		    processInventory.setCodeM(imageInByte);
    	    }catch(IOException e){
    	        System.out.println(e.getMessage());
    	    }
        	
        

             
            model.put("g", processInventory);
            maps.add(model);
		}
    	
    	
        // 解决导出文件名中文乱码  
        String filename = new String(("跟踪单").getBytes("gb2312"), "iso8859-1");  
        response.setHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");  
        
//        InputStream inputStream = ProcessInventoryController.class.getClassLoader()
//        		.getResourceAsStream("jxls-template/g.xls");
//        String path = ResourceUtils.getURL("classpath:").getPath();
//        ClassPathResource classPathResource = new ClassPathResource("g.xls");
//        InputStream inputStream =    classPathResource.getInputStream();
//        InputStream inputStream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("g.xlsx");
//        InputStream inputStream = this.getClass().getClassLoader().getSystemResourceAsStream("g.xlsx");
        ClassPathResource resource = new ClassPathResource("ge2.xlsx");
        InputStream inputStream = resource.getInputStream();
        System.err.println(inputStream== null);
        model2.put("list", maps);
        JxlsUtils.exportExcel(inputStream, response.getOutputStream(), model2);
    
    }

    /**
     * 修改保存加工库存
     */
    @RequiresPermissions("process:inventory:edit")
    @Log(title = "加工库存", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ProcessInventory processInventory)
    {
        processInventory.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(processInventoryService.updateProcessInventory(processInventory));
    }

    /**
     * 删除加工库存
     */
    @RequiresPermissions("process:inventory:remove")
    @Log(title = "加工库存", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return processInventoryService.deleteProcessInventoryByIds(ids);
    }
}
